window['PP.wx.buy.time'] && window['PP.wx.buy.time'].push(new Date());
function $addToken(url, type, skey) {
	var token = $getToken(skey);
	if (url == "" || (url.indexOf("://") < 0 ? location.href: url).indexOf("http") != 0) {
		return url;
	}
	if (url.indexOf("#") != -1) {
		var f1 = url.match(/\?.+\#/);
		if (f1) {
			var t = f1[0].split("#"),
			newPara = [t[0], "&g_tk=", token, "&g_ty=", type, "#", t[1]].join("");
			return url.replace(f1[0], newPara);
		} else {
			var t = url.split("#");
			return [t[0], "?g_tk=", token, "&g_ty=", type, "#", t[1]].join("");
		}
	}
	return token == "" ? (url + (url.indexOf("?") != -1 ? "&": "?") + "g_ty=" + type) : (url + (url.indexOf("?") != -1 ? "&": "?") + "g_tk=" + token + "&g_ty=" + type);
};
function $formatPrix(prix, formatStr) {
	var arrPrix = (prix + ".").split("."),
	arrFormat = (formatStr + ".").split("."),
	formatLen = arrFormat[1].length;
	return [( + prix).toFixed(formatLen), arrPrix[0], arrPrix[1]];
};
function $getCookie(name) {
	var reg = new RegExp("(^| )" + name + "(?:=([^;]*))?(;|$)"),
	val = document.cookie.match(reg);
	return val ? (val[2] ? unescape(val[2]) : "") : null;
};
function $getToken(skey) {
	var skey = skey ? skey: $getCookie("skey");
	return skey ? $time33(skey) : "";
};
function $itilReport(option) {
	var opt = {
		bid: "1",
		mid: "01",
		res: [],
		onBeforeReport: null,
		delay: 5000
	}
	for (var k in option) {
		opt[k] = option[k];
	}
	if (opt.res.length > 0) {
		window.reportWebInfo = function(json) {};
		window.setTimeout(function() {
			opt.onBeforeReport && opt.onBeforeReport(opt);
			var pstr = opt.bid + opt.mid + "-" + opt.res.join("|");
			var url = "http://focus.paipai.com/webreport/ReportWebInfo?report=" + pstr + "&t=" + new Date() / 1000;
			$loadUrl({
				url: url
			});
		},
		opt.delay);
	}
};
function $loadImg(obj, attr) {
	if (!obj) return;
	var attr = attr || "back_src",
	images = obj.getElementsByTagName("IMG");
	for (var i = 0, len = images.length; i < len; i++) {
		var oImg = images[i],
		src = oImg.getAttribute(attr);
		'' == oImg.src && src && (oImg.src = src);
	}
};
function $loadUrl(o) {
	o.element = o.element || 'script';
	var el = document.createElement(o.element);
	el.charset = o.charset || 'utf-8';
	o.onBeforeSend && o.onBeforeSend(el);
	el.onload = el.onreadystatechange = function() {
		if (/loaded|complete/i.test(this.readyState) || navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
			o.onLoad && o.onLoad();
			clear();
		}
	};
	el.onerror = function() {
		clear();
	};
	el.src = o.url;
	document.getElementsByTagName('head')[0].appendChild(el);
	function clear() {
		if (!el) {
			return;
		}
		el.onload = el.onreadystatechange = el.onerror = null;
		el.parentNode && (el.parentNode.removeChild(el));
		el = null;
	}
};
function $namespace(name) {
	for (var arr = name.split(','), r = 0, len = arr.length; r < len; r++) {
		for (var i = 0, k, name = arr[r].split('.'), parent = {}; k = name[i]; i++) {
			i === 0 ? eval('(typeof ' + k + ')==="undefined"?(' + k + '={}):"";parent=' + k) : (parent = parent[k] = parent[k] || {});
		}
	}
};
function $time33(str) {
	for (var i = 0, len = str.length, hash = 5381; i < len; ++i) {
		hash += (hash << 5) + str.charAt(i).charCodeAt();
	};
	return hash & 0x7fffffff;
};
$namespace("PP.wx.buy");
true || $zepto();
PP.wx.buy = {
	confirmUrl: "http://m.buy.qq.com/p/cart/order/wxconfirm.xhtml?ic={#itemCode#}&attr={#stockAttr#}&bc={#itemCount#}&adid={#adid#}&{#params#}",
	dealCode: "",
	orderMt: "0",
	errMsg: {
		"201": "您还有多笔订单尚未支付，请先取消您不需要的订单",
		"103": "抱歉，此商品已售完或下架",
		"466": "抱歉，此商品已售完或下架",
		"33": "抱歉，您已购的商品超过了卖家设定的最大购买数量",
		"258": "系统繁忙，请稍后重试",
		"195": "抱歉，不能购买自己店铺中出售的商品",
		"516": "抱歉，此商品已下架",
		"432": "操作过于频繁，请稍后重试",
		"444": "操作过于频繁，请稍后重试",
		"40": "操作过于频繁，请稍后重试",
		"112": "抱歉，您已被禁止购买商品，请与客服联系",
		"24": "抱歉，您已被禁止购买商品，请与客服联系",
		"23": "抱歉，您的账户已被冻结，请与客服联系",
		"108": "抱歉，订单金额超出范围，请重新下单",
		"490": "抱歉，您无法购买该商品",
		"358": "抱歉，购买失败，商品库存不足",
		"696": "抱歉，购买失败，商品库存不足",
		"445": "抱歉，购买失败，请重试",
		"192": "抱歉，此商品已售完"
	}
};
PP.wx.buy.init = function() {
	$loadImg($("#orderForm")[0]);
	this.bindEvents();
	this.initShare();
	this.initStore();
	this.handleFeeCharge();
};
PP.wx.buy.addrList = function() {
	this.bindAddrListEvent();
	this.initShare();
};
PP.wx.buy.address = function() {
	this.formRule = {
		"name": {
			emptyMsg: "请填写收货人姓名",
			itemName: "收货人姓名",
			reg: /^[\u0391-\uFFE5a-zA-Z]+$/,
			errMsg: "请填写正确的收货人姓名",
			dByte: true,
			required: true,
			maxLen: 10,
			minLen: 4
		},
		"mobile": {
			emptyMsg: "请填写收货人的联系电话",
			itemName: "收货人联系电话",
			reg: /^(1[3584]\d{9})$/,
			errMsg: "请输入正确的手机号码",
			required: true,
			minLen: 5
		},
		"address": {
			emptyMsg: "请填写收货人的详细地址",
			itemName: "详细地址",
			reg: /.*/,
			errMsg: "请填写正确的地址",
			dByte: true,
			required: true,
			maxLen: 50,
			minLen: 4
		}
	};
	this.initAddrParam();
	this.initAddrArea();
	this.bindAddrEvent();
	this.initShare();
};
PP.wx.buy.initStore = function() {
	/*
	var paramStore = new store("confirmOrder");
	var backUrl = $("#vmReferer").val();
	if (backUrl && (backUrl.indexOf("wxdetails") >= 0 || backUrl == "$vmReferer")) {
		var params = $("#baseParams").val();
		if (params) {
			params = params.substr(2);
		}
		var ps = {
			itemCode: $("#orderItemCode").val(),
			stockAttr: $("#orderStockAttr").val(),
			itemCount: $("#orderItemCount").val(),
			sellerUin: $("#orderSellerUin").val(),
			baseParams: params,
			adid: $("#addressId").val()
		}
		paramStore.setStore(ps, true);
	}
	var nps = JSON.parse(paramStore.getStore());
	if (nps) {
		$("#orderItemCount").val(nps.itemCount);
		$("#goodsNumTxt").text(nps.itemCount);
		$("#itemPrice").text(nps.tPrice);
	}
	var farePrice = $("#fareVal").attr("price");
	if (farePrice != "0") {
		if (nps && nps.tPayPrice) {
			$("#totItemPrice").text(nps.tPayPrice);
		} else {
			var pri = nps && nps.tPrice ? nps.tPrice: $("#itemPrice").attr("price");
			$("#totItemPrice").text($formatPrix(parseFloat(pri) + parseFloat(farePrice), "x.xx")[0]);
		}
		$("#totPayPriceBlock").show();
	}
	var backLink = $(".mod_bar_back a"),
	bhref = backLink.attr("href"),
	_bid = $getCookie("_bid");
	if (_bid) {
		backLink.attr("href", bhref + "&bid=" + _bid);
	}
	
	*/
};

PP.wx.buy.bindEvents = function() {
	var that = this,
	buyBtn = $("#buyBtn"),
	wxpay = $("#wxpay").val(),
	itemCount = $("#orderItemCount").val();
	if (!this.lowWeixin() || wxpay == "0") {
		buyBtn.addClass("btn_buy_disabled");
		buyBtn.text("微信支付 不可用状态");
	} else if (itemCount == "0") {
		buyBtn.addClass("btn_buy_disabled");
		buyBtn.text("微信支付 库存不足");
	} else {
		buyBtn.on("click", function() {
			if (buyBtn.hasClass("btn_buy_disabled")) return;
			var stockCount = $("#orderStockCount").val();
			if (!stockCount || parseInt(stockCount, 10) == 0) {
				alert("商品没有库存");
				return;
			}
			var addressId = $("#addressId").val();
			if (addressId == "0") {
				alert("请选择收货地址");
				return;
			}
			that.handleSubmit();
		});
	}
	that.orderMt = $("#orderMt").val();
	$("#dfBuyBtn").on("click", function() {
		var addressId = $("#addressId").val();
		if (addressId == "0") {
			alert("请选择收货地址");
			return;
		}
		var itemPrice = parseFloat($("#itemPrice").text()),
		orderCodFee = parseFloat($("#orderCodFee").val() || 0) / 100,
		codCountFee = parseFloat($("#codCountFee").val() || 0) / 100,
		tPrice = $formatPrix(itemPrice + orderCodFee + codCountFee, "x.xx")[0];
		$("#tipsPriceTxt").text(tPrice);
		if (codCountFee > 0 || orderCodFee > 0) {
			var tipsStr = '(含货到付款';
			if (codCountFee > 0) {
				var ccFee = $formatPrix(codCountFee, "x.xx")[0],
				ind = ccFee.indexOf(".");
				if (ccFee.substr(ind) == ".00") {
					ccFee = ccFee.substr(0, ind);
				}
				tipsStr += '服务费' + ccFee + '元'; (orderCodFee > 0) && (tipsStr += "，");
			}
			if (orderCodFee > 0) {
				var ocFee = $formatPrix(orderCodFee, "x.xx")[0],
				ind = ocFee.indexOf(".");
				if (ocFee.substr(ind) == ".00") {
					ocFee = ocFee.substr(0, ind);
				}
				tipsStr += '运费' + ocFee + '元';
			}
			$("#tipsSevOuter").text(tipsStr + ")");
		}
		that.cover(true, true);
		$("#payTipsFloat").show();
	});
	$("#surePayBtn").on("click", function() {
		$("#orderPayType").val("1");
		$("#orderMt").val($("#orderCodMt").val());
		$("#payTipsFloat").hide();
		that.cover(false);
		that.codHandleSubmit();
	});
	
	$("#sendType").on("change", that.handleFeeCharge);
	
	$("#cancelPayBtn").on("click", function() {
		$("#payTipsFloat").hide();
		$("#orderPayType").val("2");
		$("#orderMt").val(that.orderMt);
		that.cover(false);
	});
	/*
	$("#addressItem").on("click",
	function() {
		location.href = $("#addressBtn").attr("href");
	});
	*/
	/*
	 *
	$(".address_blank").on("click",
	function() {
		location.href = $(".address_ico").attr("href");
	});
	 */

	$("[tag=comm_count]").bind("input", function() {
	   var num = $(this).val();
	   if (num == '') {
		   return;
	   }
       var that = this,
       maxBuyNum = $(this).attr("maxBuyNum"),
       curBuyNum;
	  
	   if (isNaN(num)) {
		   num = 1;
		   alert("购买数量只能输入数字，已自动修改")
	   } else if ( 0 >= num) {
		   num = 1;
		   alert("至少购买一件");
	   } else if (/^\d+$/.test(num) == false) {
		   num = 1;
		   alert("购买数量只能输入整数，已自动修改");
	   }
	   /*
	   var inventory = $(this).attr("inventory");
       if(inventory == 1){
       	if(num > maxBuyNum){
       		this.alert("当前剩余量:"+maxBuyNum);
       		curBuyNum = maxBuyNum;
       	}else{
       		curBuyNum = num;
       	}
       	$(this).val(maxBuyNum);
       }else{
       	$(this).val(num);
       	curBuyNum = num;
       }
       */
       
	   var pid = $(this).attr("pid");
	    utils.ajaxReq({
	        url: window.basePath,
	        dataType: "json",
	        type: "POST",
	        data : {
				'module': 'product',
		        'method' : 'updateOrderDetail',
		        'params' : '{"oid":' + window.id + ',"sid":-1,"pid":' + pid +  ',"count":' + num + ',"type":"buy"}',
			}
	    }, function (b) {
	        $(that).val(num);
	    	curBuyNum = num;
	        
	        var iPrice = $("#iPrice").attr("price");
	        var totalPrice = iPrice * curBuyNum;
	        
	        var sendType = $("#sendType");
	        var a = sendType[0];
	        var c = a.options[a.selectedIndex];
	        var curMtype = c.getAttribute("mtype");
	        var cost = c.getAttribute("cost");

	        if(window.type == 'point'){
	        	cost =  parseInt(cost);
	        }else{
	        	cost =  parseFloat(cost);
	        }
	        if (curMtype == "pickup" || curMtype == "" ) {
	        } else {
	        	if(cost == '-1'){
	        	}else{
	        		totalPrice = cost+totalPrice;
	        	}
	        }
	        
	        //计算价格
	        totalPrice = totalPrice.toFixed(2);
	        $("#totalPrice").text(totalPrice);
	    });
    });
	
	var itemPrice = $("#itemPrice"),
	totItemPrice = $("#totItemPrice"),
	fareVal = $("#fareVal");
	$("#orderItemCount").on("change",
	function() {
		$("#goodsNumTxt").text(this.value);
		var price = parseFloat(itemPrice.attr("price")),
		farePrice = fareVal.attr("price"),
		totPrice = $formatPrix(price * this.value, "x.xx")[0];
		itemPrice.text(totPrice);
		var totPayPrice = "";
		if (farePrice && farePrice != "0") {
			farePrice = parseFloat(farePrice);
			var totPayPrice = $formatPrix(price * this.value + farePrice, "x.xx")[0];
			totItemPrice.text(totPayPrice);
		} else totPayPrice = totPrice;
		var paramStore = new store("confirmOrder");
		var params = $("#baseParams").val();
		if (params) {
			params = params.substr(2);
		}
		var ps = {
			itemCode: $("#orderItemCode").val(),
			stockAttr: $("#orderStockAttr").val(),
			itemCount: this.value,
			sellerUin: $("#orderSellerUin").val(),
			baseParams: params,
			adid: $("#addressId").val(),
			tPrice: totPrice,
			tPayPrice: totPayPrice
		}
		paramStore.setStore(ps, true);
	});
	var hh = $(".goods").height();
	if (hh && hh != "auto") {
		$(".goods_img").height(hh - 20);
	}
};
PP.wx.buy.handleFeeCharge = function () {
	var a = $("#sendType")[0];
	var c = a.options[a.selectedIndex];
    var curMtype = c.getAttribute("mtype");
    var cost = c.getAttribute("cost");
    if(window.type == 'point'){
    	cost =  parseInt(cost);
    }else{
    	cost =  parseFloat(cost);
    }
    if (curMtype == "pickup") {
    	$("#toAddrList").hide();
    	$("#toStoreList").show();
    } else {
    	$("#toAddrList").show();
    	$("#toStoreList").hide();
    }
   
    var countNum = $("#countNum");
	var curBuyNum = countNum.val();
	var iPrice =  $("#iPrice").attr("price");
	var totalPrice = iPrice * curBuyNum;
	if(cost != '-1'){
		totalPrice = cost+totalPrice;
	}
	totalPrice = totalPrice.toFixed(2);
	$("#totalPrice").text(totalPrice);
}
PP.wx.buy.handleSubmit = function() {
	var that = this,
	form = $("#orderForm"),
	buyBtn = $("#buyBtn");
	buyBtn.addClass("btn_buy_disabled");
	$("#loadingImg").show();
	$("#buyBtns").hide();
	that.cover(true);
	var url = form.attr("action");
	if (that.dealCode) {
		var baseParams = url.substr(url.indexOf("?"));
		url = "http://m.buy.qq.com/p/cart/order/wxpay.xhtml" + baseParams;
	}
	$.ajax({
		type: "post",
		url: $addToken(url, "fr"),
		data: form.serialize(),
		dataType: "json",
		success: function(json) {
			if (json.errCode == "0") {
				var newUrl = "http://pay.paipai.com/index.php?c=pay&m=touch&datatype=jsonp";
				var sellerUin = json.data.sellerUin;
				if (json.data.dealCode) {
					that.dealCode = json.data.dealCode;
				}
				$.ajax({
					url: newUrl,
					type: "get",
					dataType: "jsonp",
					data: {
						"wg_uin": json.data.buyerUin,
						"wg_skey": json.data.skey,
						"appid": json.data.appid,
						"dealid": json.data.dealCode ? json.data.dealCode: that.dealCode
					},
					success: function(json) {
						$("#loadingImg").hide();
						that.cover(false);
						if (json.errno == "0") {
							var n = json.data;
							WeixinJSBridge && WeixinJSBridge.invoke("getBrandWCPayRequest", n,
							function(t) {
								if (t.err_msg == "get_brand_wcpay_request:ok") {
									try {
										$itilReport({
											bid: "7",
											mid: "02",
											res: ["0:1", "1:1"],
											delay: 0
										});
									} catch(e) {}
									window.setTimeout(function() {
										location.href = "http://weigou.qq.com/mmwg/paysuc.shtml?bid=" + sellerUin;
									},
									100);
								} else if (t.err_msg == "get_brand_wcpay_request:cancel") {
									try {
										$itilReport({
											bid: "7",
											mid: "02",
											res: ["1:1", "2:1"],
											delay: 0
										});
									} catch(e) {}
								} else if (t.err_msg == "get_brand_wcpay_request:fail") {
									try {
										$itilReport({
											bid: "7",
											mid: "02",
											res: ["0:0", "1:1"],
											delay: 0
										});
									} catch(e) {}
									alert("支付失败,请稍候再试");
								} else if (t.err_msg == "system:function_not_exist") {
									try {
										$itilReport({
											bid: "7",
											mid: "02",
											res: ["1:1", "3:1"],
											delay: 0
										});
									} catch(e) {}
									alert("系统不支持微信支付");
								} else {
									try {
										$itilReport({
											bid: "7",
											mid: "02",
											res: ["1:1", "7:1"],
											delay: 0
										});
									} catch(e) {}
									alert("发生未知错误。" + t.err_msg);
								}
								$("#buyBtns").show();
							});
						} else {
							try {
								$itilReport({
									bid: "7",
									mid: "02",
									res: ["1:0"],
									delay: 0
								});
							} catch(e) {}
							alert("支付失败,请稍候再试");
						}
						buyBtn.removeClass("btn_buy_disabled");
					},
					error: function(xhr, type) {
						buyBtn.removeClass("btn_buy_disabled");
						$("#buyBtns").show();
						$("#loadingImg").hide();
						that.cover(false);
						alert("支付失败,请稍候再试");
					}
				});
				try {
					$itilReport({
						bid: "7",
						mid: "02",
						res: ["4:1"],
						delay: 0
					});
				} catch(e) {}
			} else {
				buyBtn.removeClass("btn_buy_disabled");
				$("#buyBtns").show();
				$("#loadingImg").hide();
				that.cover(false);
				var alertMsg = that.errMsg[json.errCode];
				if (json.errCode == "201") {
					try {
						$itilReport({
							bid: "7",
							mid: "02",
							res: ["5:1"],
							delay: 0
						});
					} catch(e) {}
				} else if (json.errCode == "-199") {
					try {
						$itilReport({
							bid: "8",
							mid: "04",
							res: ["2:1"],
							delay: 0
						});
					} catch(e) {}
				} else if (json.errCode == "33") {
					try {
						$itilReport({
							bid: "8",
							mid: "04",
							res: ["3:1"],
							delay: 0
						});
					} catch(e) {}
				} else if (json.errCode == "23") {
					try {
						$itilReport({
							bid: "8",
							mid: "04",
							res: ["4:1"],
							delay: 0
						});
					} catch(e) {}
				} else if (json.errCode == "6") {
					try {
						$itilReport({
							bid: "8",
							mid: "04",
							res: ["5:1"],
							delay: 0
						});
					} catch(e) {}
				} else {
					try {
						$itilReport({
							bid: "7",
							mid: "02",
							res: ["4:0"],
							delay: 0
						});
					} catch(e) {}
				}
				alert(alertMsg ? alertMsg: "提交订单失败,请稍候再试");
			}
		},
		error: function(xhr, type) {
			buyBtn.removeClass("btn_buy_disabled");
			$("#buyBtns").show();
			$("#loadingImg").hide();
			that.cover(false);
			try {
				$itilReport({
					bid: "7",
					mid: "02",
					res: ["4:0"],
					delay: 0
				});
			} catch(e) {}
			alert("提交订单失败,请稍候再试");
		}
	});
};
PP.wx.buy.codHandleSubmit = function() {
	var that = this;
	var sendType = $("#sendType").val();
	
	var type = window.type;
	
	var payType = $("#payType").val();
	
	var totalPrice =window.totalPrice;
	
	var sid = window.sid;
	var fullName = window.fullName;
	var phone  = window.phone ;
	var address =  window.address;
	var id =  window.id;
	
	if(sendType == '-1'){
		alert("请选择配送方式");
		return;
	}
	
	 if (sendType == "pickup") {
     	if (sid == -1) {
     		alert("请选择自提门店");
     		 return ;
     	}
    } else {
		if (fullName == '' || phone == '' || address == '') {
			alert("请填写收货信息");
			return ;
		}
		sid = -1;
    }
	
	if(payType == '-1'){
		alert("请选择支付方式");
		return false;
	}
	var param = id == '' ? '' : ',"id":' + parseInt(id);
	
	
	//form = $("#orderForm");
	$("#loadingImg").show();
	$("#disableSurePayBtn").show();
	$("#buyBtns").hide();
	$("#surePayBtn").hide();
	
	that.cover(true);
	var remark = $("#message_0").val();
	//var remark='';
	
	$.ajax({
		type: "post",
		url:  window.basePath,
		data: {
        	module: 'product',
	        method: 'submitOrder',
	        params: '{"sid":' + sid + ',"type":"' +type + '","fullName":"' + fullName
	        	+ '","phone":"' + phone + '","address":"' + address + '","remark":"'
	        	+ remark + '","paytype":"' + payType + '","dtype":"' + sendType + '"' + param + '}',
        },
		dataType: "json",
		success: function(d) {
//			console.log(d);
        	if (typeof(d.code) !== "undefined") {
        		alert(d.msg);
        		$("#loadingImg").hide();
        		$("#disableSurePayBtn").hide();
        		$("#buyBtns").show();
        		$("#surePayBtn").show();
        		that.cover(false);
        		return;
			}
			if (typeof(d.code) === "undefined") {
				 if (payType === 'wxpay') {
        			 try {
        				 var id = d.id;
        				 var price = d.price;
        				 WeixinJSBridge.invoke('getBrandWCPayRequest', d.pkg ,function(res){
                       		WeixinJSBridge.log(res.err_msg);
                       		// this.alert(res.err_code + ';' +res.err_desc + ';' +res.err_msg);
                       		if (res.err_msg == 'get_brand_wcpay_request:ok') {
                       			location.href = window.hrefPath + '&module=product&method=orderSuccess&params={"tplid":' + window.tplid
                       			+ ',"id":' + id + window.rootId + '}';
                       		} else {
                       			utils.ajaxReq({
                                    url: window.basePath,
                                    dataType: "json",
                                    type: "POST",
                                    data: {
                                    	module: 'product',
                            	        method: 'cancelWxOrder',
                            	        params: '{"oid":' + id + '}'
                                    }
                                }, function (e) {
                                	if (res.err_msg == 'get_brand_wcpay_request:cancel') {
    	                       		//	this.alert("操作已取消");
    	                       		} else if (res.err_msg == 'get_brand_wcpay_request:fail') {
    	                       			alert("网络错误发送失败，请稍后再试");
    	                       		} else if (res.err_msg == 'access_control:not_allow' || res.err_msg == 'system:access_denied') {
    	                       			alert("商家尚未开通微信支付");
    	                       		} else {
    	                       			alert(res.err_msg);
    	                       		}
                           			$("#loadingImg").hide();
                            		$("#disableSurePayBtn").hide();
                            		$("#buyBtns").show();
                            		$("#surePayBtn").show();
                            		that.cover(false);
                                });
                       		}
                       	});
        			 } catch(e) {
        				 alert("操作失败，请确保在微信浏览器中操作");
        				$("#loadingImg").hide();
                 		$("#disableSurePayBtn").hide();
                 		$("#buyBtns").show();
                 		$("#surePayBtn").show();
                 		that.cover(false);
        			 }
				 } else if (payType === 'upay') {
            		 if(d.success == "first_pay"){
            			$("#loadingImg").hide();
                 		$("#disableSurePayBtn").hide();
                 		$("#buyBtns").show();
                 		$("#surePayBtn").show();
          				location.href=d.url;
          			}
             	 } else {
					var id = d.id;
	     			var price = d.price;
	     			var points = d.points;
	     			var ptype = d.payType;
	     			location.href = window.hrefPath + '&module=product&method=orderSuccess&params={"tplid":' + window.tplid
		             	+ ',"id":' + id + window.rootId + '}';
				 }
			} else {
				alert("请求遇到了点问题，请重试。");
        		$("#loadingImg").hide();
        		$("#disableSurePayBtn").hide();
        		$("#buyBtns").show();
        		$("#surePayBtn").show();
        		that.cover(false);
        	}
		},
		error: function(xhr, type) {
			$("#surePayBtn").show();
			$("#buyBtns").show();
			$("#loadingImg").hide();
			$("#disableSurePayBtn").hide();
			that.cover(false);
//    		params = '&module=product&method=getOrderDetail&params={"tplid":2,"id":' + window.id +  window.rootId + '}';
//	        location.href = window.hrefPath + params;
			
			try {
				$itilReport({
					bid: "7",
					mid: "02",
					res: ["6:0"],
					delay: 0
				});
			} catch(e) {}
			alert("提交订单失败,请稍候再试");
		}
	});
};
PP.wx.buy.bindAddrListEvent = function() {
	var that = this;
	var paramStore = new store("confirmOrder");
	var ps = paramStore.getStore();
	if (ps) {
		ps = JSON.parse(ps);
	}
	var adid = $("#adid").val();
	if (!adid || adid == "0") {
		if (ps && ps.adid && ps.adid != "0") {
			$("#itemList .address_item").each(function(ind, item) {
				if ($(item).attr("adid") == ps.adid) {
					$(item).find(".address_check").removeClass("address_check").addClass("address_checked");
				}
			});
		} else {
			var addItem = $("#itemList .address_item").first();
			if (addItem) {
				addItem.find(".address_check").removeClass("address_check").addClass("address_checked");
				adid = addItem.attr("adid");
			}
		}
	}
	$("#returnBtn").on("click",
	function() {
		location.href = that.confirmUrl.replace("{#itemCode#}", ps.itemCode).replace("{#stockAttr#}", encodeURIComponent(ps.stockAttr)).replace("{#itemCount#}", ps.itemCount).replace("{#adid#}", adid ? adid: ps.adid).replace("{#params#}", ps.baseParams) + "&isret=1";
	});
	$("#itemList .address_add").on("click",
	function(e) {
		var len = parseInt($("#itemList").attr("data-size"), 10);
		e.preventDefault();
		if (len && len >= 10) {
			alert("您最多可以保存10条收货地址");
			return false;
		}
		location.href = $("#addAddrBtn").attr("href");
	});
	$("#itemList .address_item").on("click",
	function(e) {
		var tar = e.target;
		if (tar.tagName.toLowerCase() == "a" || !ps) return;
		var adid = $(this).attr("adid");
		location.href = that.confirmUrl.replace("{#itemCode#}", ps.itemCode).replace("{#stockAttr#}", encodeURIComponent(ps.stockAttr)).replace("{#itemCount#}", ps.itemCount).replace("{#adid#}", adid).replace("{#params#}", ps.baseParams);
	});
};
PP.wx.buy.initAddrParam = function() {
	this.provinceNode = $("#province");
	this.cityNode = $("#city");
	this.regionNode = $("#regionId");
	this.curPro = this.provinceNode.attr("data-current");
	this.curCity = this.cityNode.attr("data-current");
	this.curReg = this.regionNode.attr("data-current");
	var paramStore = new store("confirmOrder");
	var ps = paramStore.getStore();
	if (ps) {
		ps = JSON.parse(ps);
		if (!ps.adid || ps.adid == "0") {
			$("#cancel_addr").attr("href", this.confirmUrl.replace("{#itemCode#}", ps.itemCode).replace("{#stockAttr#}", encodeURIComponent(ps.stockAttr)).replace("{#itemCount#}", ps.itemCount).replace("{#adid#}", "0").replace("{#params#}", ps.baseParams));
		}
		$("#cancel_addr").attr("href");
	}
};
PP.wx.buy.initAddrArea = function() {
	var _this = this,
	pvid,
	ctid;
	if (_this.curPro) {
		areaUtils.setOptionInfo("province", "province", 0, "", _this.curPro);
	} else {
		areaUtils.setOptionInfo("province", "province", 0, "选择省");
	}
	pvid = _this.provinceNode.val();
	if (pvid == "32" || pvid == "33") {
		areaUtils.setOptionInfo("city", "city", pvid, "", _this.curCity);
		_this.regionNode.empty();
		_this.regionNode.parent().addClass("qb_none");
		return;
	}
	if (_this.curCity) {
		areaUtils.setOptionInfo("city", "city", pvid, "", _this.curCity);
		if (pvid == "0" || pvid == "1" || pvid == "2" || pvid == "3") {
			_this.cityNode.parent().addClass("qb_none");
		}
	}
	if (_this.curReg && _this.curReg != "0") {
		ctid = _this.cityNode.val();
		areaUtils.setOptionInfo("regionId", "area", ctid, "", _this.curReg);
		if (_this.regionNode.attr("len") == "0") {
			_this.regionNode.parent().addClass("qb_none");
		}
	}
};
PP.wx.buy.bindAddrEvent = function() {
	$("#province").on("change", $.proxy(this.provinceChange, this));
	$("#city").on("change", $.proxy(this.cityChange, this));
	$("#save_addr").on("click", $.proxy(this.saveAddr, this));
	$("#address").on("focus",
	function() {
		var cover = $("#addCover");
		if (!cover || cover.length <= 0) {
			cover = $("<div id='addCover'></div>");
			var top = $(".formbtn").position().top + 20,
			left = $("#cancel_addr").position().left + 10,
			width = $("#cancel_addr").width(),
			height = $("#cancel_addr").height();
			cover.css({
				"width": width,
				"height": height,
				"position": "absolute",
				"top": top,
				"left": left,
				"z-index": 99
			});
			cover.appendTo(document.body);
		}
		cover.show();
	});
	$("#address").on("blur",
	function() {
		window.setTimeout(function() {
			$("#addCover").hide();
		},
		0);
	});
};
PP.wx.buy.provinceChange = function() {
	var _this = this,
	pvid = _this.provinceNode.val();
	if (pvid == -1) {
		_this.cityNode.html("<option value='-1' selected='selected'>选择市</option> ");
		_this.cityNode.parent().removeClass("qb_none");
		_this.regionNode.html("<option value='-1' selected='selected'>选择区</option> ");
		_this.regionNode.parent().removeClass("qb_none");
		return false;
	}
	areaUtils.setOptionInfo("city", "city", pvid, "");
	if (pvid == "0" || pvid == "1" || pvid == "2" || pvid == "3") {
		_this.cityNode.parent().addClass("qb_none");
	} else {
		_this.cityNode.parent().removeClass("qb_none");
	}
	_this.cityChange();
};
PP.wx.buy.cityChange = function() {
	var _this = this,
	ctid = _this.cityNode.val();
	areaUtils.setOptionInfo("regionId", "area", ctid, false);
	if (_this.regionNode.attr("len") == "0") {
		_this.regionNode.parent().addClass("qb_none");
	} else {
		_this.regionNode.parent().removeClass("qb_none");
	}
};
PP.wx.buy.showbubble = function(a,b){
        if (a) {
            b = b || 1500;
            var c = $("#bubble");
            c.css("opacity", 1), c.hasClass("qb_none") || c.html(a), c.html(a).removeClass("qb_none"), setTimeout(function () {
                c.animate({
                    opacity: 0
                }, 500, "ease", function () {
                    $(this).addClass("qb_none").removeAttr("style")
                })
            }, b)
        }
}
PP.wx.buy.saveAddr = function(e) {
	if (!this.checkAddr()) {
		return;
	}
	
	var fullName = $('#name').val();
    var phone = $('#mobile').val();
    var address = $('#address').val();
   
	var b = {
		'module': 'product',
        'method' : 'updateUserInfo',
        'params' : '{"fullname":"' + fullName + '","phone":"' + phone + '","address":"' + address + '"}',
	};
    utils.ajaxReq({
        url: window.basePath,
        dataType: "json",
        type: "POST",
        data: b
    }, function (b) {
    	var params;
    	if (this.preOid == undefined) {
    		params = '&module=product&method=confirmOrder&params={"type":"buy","sid":-1' + window.rootId + window.ptype + window.dtype + '}';
    	} else {
    		params = '&module=product&method=getOrderDetail&params={"tplid":2,"id":' + window.preOid +  window.rootId + window.ptype + window.dtype + '}';
    	}
        location.href = window.hrefPath + params;
    });
   
	/*
	var that = this;
	var form = $(e.target).parents('form');
	form.attr("action", $addToken(form.attr("action"), "fr"));
	form.submit();
	*/
	
};
PP.wx.buy.checkAddr = function(e) {
	var _this = this,
	result = utils.validate(_this.formRule),
	validatePass = true,
	content = "",
	errNode = $("#region_msg");
	if (_this.provinceNode.val() == "-1") {
		content = "请选择区域";
		errNode.removeClass("qb_none").html(content);
		validatePass = false;
	} else if (!_this.cityNode.parent().hasClass("qb_none") && _this.cityNode.val() == "-1") {
		content = "请选择区域";
		errNode.removeClass("qb_none").html(content);
		validatePass = false;
	} else if (!_this.regionNode.parent().hasClass("qb_none") && _this.regionNode.val() == "-1") {
		content = "请选择区域";
		errNode.removeClass("qb_none").html(content);
		validatePass = false;
	} ! validatePass && result && alert.(content);
	return validatePass && result;
};
PP.wx.buy.lowWeixin = function() {
	var ua = navigator.userAgent.toLowerCase();
	return ua.match(/micromessenger\/5/) ? true: false;
}
PP.wx.buy.initShare = function() {
	var paramStore = new store("cache_cmdtyshare");
	var ps = paramStore.getStore();
	if (ps) {
		ps = JSON.parse(ps);
	} else return;
	var shareConfig = {};
	shareConfig.img_url = ps.img_url;
	shareConfig.img_width = ps.img_width;
	shareConfig.img_heigth = ps.img_heigth;
	shareConfig.link = ps.link;
	shareConfig.desc = ps.desc;
	shareConfig.title = ps.title;
	if (window.WeixinJSBridge) {
		WXReadyFn();
	} else {
		window._timeout_WX_regist1 = setTimeout(function() {
			WXReadyFn();
		},
		1000);
		try {
			document.addEventListener("WeixinJSBridgeReady",
			function() {
				clearTimeout(window._timeout_WX_regist1);
				WXReadyFn();
			});
		} catch(e) {}
	}
	function WXReadyFn() {
		try {} catch(e) {}
		try {
			WeixinJSBridge.on("menu:share:timeline",
			function(argv) {
				WeixinJSBridge.invoke("shareTimeline", {
					"img_url": shareConfig.img_url,
					"img_width": shareConfig.img_width,
					"img_height": shareConfig.img_height,
					"link": shareConfig.link,
					"desc": shareConfig.desc,
					"title": shareConfig.title
				},
				function(res) {});
			});
			if (/android/i.test(navigator.userAgent)) {
				WeixinJSBridge.on("menu:share:weibo",
				function(argv) {
					WeixinJSBridge.invoke("shareWeibo", {
						"url": shareConfig.link,
						"content": shareConfig.title + ' ' + shareConfig.desc
					},
					function(res) {});
				});
			} else {
				WeixinJSBridge.on("menu:share:weibo",
				function(argv) {
					WeixinJSBridge.invoke("shareWeibo", {
						"img_url": shareConfig.img_url,
						"img_width": shareConfig.img_width,
						"img_height": shareConfig.img_height,
						"link": shareConfig.link,
						"desc": shareConfig.desc,
						"title": shareConfig.title
					},
					function(res) {});
				});
			}
			WeixinJSBridge.on("menu:share:appmessage",
			function(argv) {
				WeixinJSBridge.invoke("sendAppMessage", {
					"img_url": shareConfig.img_url,
					"img_width": shareConfig.img_width,
					"img_height": shareConfig.img_height,
					"link": shareConfig.link,
					"desc": shareConfig.desc,
					"title": shareConfig.title
				},
				function(res) {});
			});
		} catch(e) {}
	}
};
PP.wx.buy.cover = function(alg, mask) {
	var cover = $("#srcCover");
	if (!cover || cover.length <= 0) {
		cover = $("<div id='srcCover'></div>");
		var width = $(document.body).width(),
		height = $(document.body).height();
		cover.css({
			"width": width,
			"height": height,
			"position": "absolute",
			"top": 0,
			"left": 0,
			"z-index": 99
		});
		cover.appendTo(document.body);
	}
	if (alg) {
		if (mask) {
			cover.addClass("mod_mask");
		} else {
			cover.removeClass("mod_mask");
		}
		cover.show();
	} else {
		cover.hide();
	}
};
var utils = {
	getRadioValue: function(a) {
		var b;
		if (b = document.getElementsByName(a), null != b) {
			var c;
			for (c = 0; c < b.length; c++)
			 if (b[c].checked)
			 return b[c].value
		}
		return null
	},
	validate: function(rule) {
		function showError(a, b) {
			alert(a);
			alg = true;
		}
		var errArr = [],
		alg = false;
		$.each(rule,
		function(id, item) {
			if (alg) return;
			var node = $("#" + id),
			value = node.val() + "";
			if (value = value.replace(/^\s*|\s*$/g, ""), !node.attr("disabled")) {
				var valLen = value.length;
				if (item.dByte && (valLen = value.replace(/[\u0391-\uFFE5]/g, "__").length), item.required)
				 if ("" == value)
				 showError(item.emptyMsg || "您输入的" + item.itemName + "不能为空", id);
				else if ("" == value || item.reg.test(value))
				 if (item.maxLen && valLen > item.maxLen)
				 showError("您输入的" + item.itemName + "必须小于" + item.maxLen + "个字符", id);
				else if (item.minLen && valLen < item.minLen)
				 showError("您输入的" + item.itemName + "不足" + item.minLen + "个字符", id);
				else if (item.minVal && value < item.minVal || item.maxVal && value > item.maxVal)
				 showError("请输入" + item.minVal + "-" + item.maxVal + "的数字", id);
				else {
					var err = $("#" + id + "_msg");
					err.addClass("qb_none"),
					item.callback && eval(item.callback + "(value, err)")
				}
				 else
				 showError(item.errMsg, id);
				else "" == value || item.reg.test(value) ? item.maxLen && valLen > item.maxLen ? showError(item.errMsg || "您输入的" + item.itemName + "超过" + item.maxLen + "个字符", id) : item.minLen && valLen < item.minLen ? showError(item.errMsg || "您输入的" + item.itemName + "不足" + item.minLen + "个字符", id) : $("#" + id + "_msg").addClass("qb_none") : showError(item.errMsg, id)
			}
		});
		return ! alg;
	},
	 ajaxReq: function (a, b, c) {
	        var d = {
	            type: "GET",
	            url: "",
	            data: "",
	            dataType: "html",
	            timeout: 5e3
	        };
	        
	        $.extend(d, a), c || (c = function () { });
	        
	        $.ajax({
	            type: d.type,
	            url: d.url,
	            data: d.data,
	            dataType: d.dataType,
	            success: function (a) {
	               // "json" == d.dataType && (a.errCode = parseInt(a.errCode, 10)), b(a)
	            	"json" == d.dataType, b(a)
	            },
	            error: c
	        })
	    },
	strReplace: function(a, b) {
		var c = a;
		for (var d in b) {
			var e = new RegExp("{#" + d + "#}", "g");
			c = c.replace(e, b[d])
		}
		return c
	},
	isEmptyObj: function(a) {
		if (!a)
		 return ! 0;
		for (var b in a)
		 return ! 1;
		return ! 0
	},
	showConfirm: function() {
		return function(a) {
			function b() {
				d(),
				e.sureFn.call(this, arguments)
			}
			function c() {
				d(),
				e.cancelFn.call(this, arguments)
			}
			function d() {
				f.contentNode.empty(),
				f.sureNode.html("确定").off("click", b),
				f.cancelNode.html("取消").off("click", c),
				f.dialogNode.addClass("qb_none")
			}
			var e = {
				describeText: "",
				sureText: "确定",
				cancelText: "取消",
				sureFn: function() {
					return ! 0
				},
				cancelFn: function() {
					return ! 0
				}
			},
			f = {
				sureNode: $("#notice-sure"),
				cancelNode: $("#notice-cancel"),
				contentNode: $("#notice-tip"),
				dialogNode: $("#message-notice")
			};
			$.extend(e, a),
			f.dialogNode.hasClass("qb_none") && (f.dialogNode.removeClass("qb_none").css({
				top: $(window).height() / 2 + window.pageYOffset - 50 + "px"
			}), f.sureNode.on("click", b), f.cancelNode.on("click", c), f.sureNode.html(e.sureText), f.cancelNode.html(e.cancelText), f.contentNode.html(e.describeText))
		}
	} (),
	cssProperty: function() {
		var a = document.documentElement,
		b = "modernizr";
		return {
			injectStyle: function(c, d) {
				var e,
				f,
				g = document.createElement("div"),
				h = document.body,
				i = h || document.createElement("body");
				return e = ["&#173;", '<style id="s', b, '">', c, "</style>"].join(""),
				g.id = b,
				(h ? g: i).innerHTML += e,
				i.appendChild(g),
				h || (i.style.background = "", a.appendChild(i)),
				f = d(g, c),
				h ? g.parentNode.removeChild(g) : i.parentNode.removeChild(i),
				!!f
			},
			pSupport: function(b) {
				for (var c = a.style, d = "Webkit Moz O ms".split(" "), e = b.charAt(0).toUpperCase() + b.substr(1), f = (e + " " + d.join(e + " ") + e).split(" "), g = null, h = 0, i = f.length; i > h; h++)
				 if (f[h] in c) {
					g = f[h];
					break
				}
				return g
			},
			has3d: function() {
				var b = !!this.pSupport("perspective");
				return b && "webkitPerspective" in a.style && this.injectStyle("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",
				function(a) {
					b = 9 === a.offsetLeft && 3 === a.offsetHeight
				}),
				b
			}
		}
	} ()
};
function store(key) {
	this.key = key;
}
$.extend(store.prototype, {
	getStore: function() {
		return localStorage.getItem(this.key);
	},
	setStore: function(value, json) {
		localStorage.setItem(this.key, json ? JSON.stringify(value) : value);
	},
	delStore: function() {
		localStorage.removeItem(this.key);
	}
});
window['PP.wx.buy'] = '21914:20131231:20140306102949';
window['PP.wx.buy.time'] && window['PP.wx.buy.time'].push(new Date());